/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pp.entites;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.io.IOException;
import java.io.Serializable;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;

/**
 *
 * @author arnaud
 */
@Entity
@Table(name = "evenement")
@XmlRootElement
@NamedQueries({
    @NamedQuery(name = "Evenement.findAll", query = "SELECT e FROM Evenement e"),
    @NamedQuery(name = "Evenement.findByIdCreateur", query = "SELECT e FROM Evenement e WHERE e.evenementPK.idCreateur = :idCreateur"),
    @NamedQuery(name = "Evenement.findByNumEvenement", query = "SELECT e FROM Evenement e WHERE e.evenementPK.numEvenement = :numEvenement"),
    @NamedQuery(name = "Evenement.findByTimestampCreation", query = "SELECT e FROM Evenement e WHERE e.timestampCreation = :timestampCreation"),
    @NamedQuery(name = "Evenement.findByTypeEvenement", query = "SELECT e FROM Evenement e WHERE e.typeEvenement = :typeEvenement"),
    @NamedQuery(name = "Evenement.findByContenu", query = "SELECT e FROM Evenement e WHERE e.contenu = :contenu")})
public class Evenement implements Serializable {
    
    	public final static int INVENTAIRE = 1;
	public final static int MESURE = 2;
	public final static int CONTROLE_TUBE = 3;
	public final static int VERIFICATION_HSE = 4;
	public final static int CREATION_TUBE = 5;
	public final static int CREATION_RACK = 6;
	public final static int MODIFICATION_PERSONNEL = 7;
        
        private static SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        
    private static final long serialVersionUID = 1L;
    @EmbeddedId
    protected EvenementPK evenementPK;
    @Basic(optional = false)
    @Column(name = "timestamp_creation")
    @Temporal(TemporalType.TIMESTAMP)
    private Date timestampCreation;
    @Basic(optional = false)
    @Column(name = "type_evenement")
    private int typeEvenement;
    @Column(name = "contenu")
    private String contenu;
    @JoinColumn(name = "idpersonnel", referencedColumnName = "id")
    @ManyToOne
    private Personnel idpersonnel;

    public Evenement() {
    }

    public Evenement(EvenementPK evenementPK) {
        this.evenementPK = evenementPK;
    }

    public Evenement(EvenementPK evenementPK, Date timestampCreation, int typeEvenement) {
        this.evenementPK = evenementPK;
        this.timestampCreation = timestampCreation;
        this.typeEvenement = typeEvenement;
    }

    public Evenement(String idCreateur, int numEvenement) {
        this.evenementPK = new EvenementPK(idCreateur, numEvenement);
    }

    /**
     * Fabrique un objet Evenement à partir d'une String json provenant d'un mobile
     * @param evtJson
     * @return 
     */
    public Evenement(String evtJson) throws IOException {
            // Recuperation de l'arbre json
            ObjectMapper obm = new ObjectMapper();
            JsonNode tree = obm.readTree(evtJson);
            // Recherche de la cle primaire de l'evenement (idCreateur + numEvenement)
            String idCreateur = tree.get("idCreateur").asText();
            int numEvt = tree.get("numEvenement").asInt();
            EvenementPK idEvt = new EvenementPK(idCreateur, numEvt);
            this.evenementPK = idEvt;

            //Affectation à l'evenement des valeurs recues 
            this.typeEvenement = tree.get("typeEvenement").asInt();
            this.timestampCreation = getDate(tree.get("timestampCreation").asText());
            this.contenu = tree.get("contenu").asText();
            // Recherche du personnel lie a l'evenement
            JsonNode personnelNode = tree.findValue("personnel");
            if(personnelNode == null || personnelNode.isNull()){
                this.idpersonnel = null;
            }else{
                int idPersonnel = personnelNode.get("id").asInt();
                /** TODO cree le personnel a partir du json dans la classe Personnel **/
                Personnel personnel = null; 
                this.idpersonnel = personnel;
            }  
    }    
    
    
    public EvenementPK getEvenementPK() {
        return evenementPK;
    }

    public void setEvenementPK(EvenementPK evenementPK) {
        this.evenementPK = evenementPK;
    }

    public Date getTimestampCreation() {
        return timestampCreation;
    }

    public void setTimestampCreation(Date timestampCreation) {
        this.timestampCreation = timestampCreation;
    }

    public int getTypeEvenement() {
        return typeEvenement;
    }

    public void setTypeEvenement(int typeEvenement) {
        this.typeEvenement = typeEvenement;
    }

    public String getContenu() {
        return contenu;
    }

    public void setContenu(String contenu) {
        this.contenu = contenu;
    }

    public Personnel getIdpersonnel() {
        return idpersonnel;
    }

    public void setIdpersonnel(Personnel idpersonnel) {
        this.idpersonnel = idpersonnel;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (evenementPK != null ? evenementPK.hashCode() : 0);
        return hash;
    }

    @Override
    public boolean equals(Object object) {
        // TODO: Warning - this method won't work in the case the id fields are not set
        if (!(object instanceof Evenement)) {
            return false;
        }
        Evenement other = (Evenement) object;
        if ((this.evenementPK == null && other.evenementPK != null) || (this.evenementPK != null && !this.evenementPK.equals(other.evenementPK))) {
            return false;
        }
        return true;
    }
    
    /**
     * retourne une chaine au format JSON representant l'evenement 
     * Cette representation est destinée au mobile
     * @return
     * @throws IOException 
     */
    public String getJson() throws IOException {
        String nullStr = null; // sert à avoir un objet de type null à mettre dans l'arbre
        
        // Construction de l'arbre json
        ObjectMapper obm = new ObjectMapper();
        ObjectNode obn = obm.createObjectNode();
        obn.put("idCreateur", this.getEvenementPK().getIdCreateur());
        obn.put("numEvenement", this.getEvenementPK().getNumEvenement());
        String timestampCrea = sdfDate.format(this.timestampCreation);
        obn.put("timestampCreation", timestampCrea);
        obn.put("typeEvenement", this.typeEvenement);
        String jsonPersonnel = null;
        if(this.idpersonnel != null){
            jsonPersonnel = obm.writeValueAsString(this.idpersonnel);
        }
        obn.put("personnel", jsonPersonnel);
        obn.put("timestampReception", nullStr);
        obn.put("timestampDiffusion", nullStr);
        obn.put("aDiffuser", false);
        obn.put("contenu", this.contenu);
        
        return obn.toString();
    }    
   

    @Override
    public String toString() {
        return "com.pp.entites.Evenement[ evenementPK=" + evenementPK + " ]";
    }
    /**
     * transforme une date au format String en Calendar grace au format sdfDate defini dans les variables d'instance 
     * @param dateString
     * @return
     */
    private Date getDate(String dateString){
        try{
            Calendar calendar = new GregorianCalendar();
            //si le contenu de la colone est nul on renvoit null
            if(dateString == null || dateString.equalsIgnoreCase("null"))
                    return null;
            Date d = sdfDate.parse(dateString);
            calendar.setTime(d);
            return calendar.getTime();
        }catch(ParseException e){
            return null;
        }
    }    
}
